package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.common.util.Trie;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApAssociateWords;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class AssociateService {

    @Autowired
    private MongoTemplate mongoTemplate;

    public ResponseResult searchAssociate(ApArticleSearchDto dto) {
//        select * from 表 where associateWords  like "%黑马%"
        if (StringUtils.isBlank(dto.getSearchWords())) {
            return null;
        }

        Query query = new Query(Criteria.where("associateWords").regex(dto.getSearchWords()));
        query.skip(0);
        query.limit(dto.getSize());

        List<ApAssociateWords> wordsList = mongoTemplate.find(query, ApAssociateWords.class);


        //使用trie来进行管理数据
        Trie trie = new Trie();
        for (ApAssociateWords apAssociateWords : wordsList) {
            trie.insert(apAssociateWords.getAssociateWords());
        }
        List<ApAssociateWords> list = trie.startWith(dto.getSearchWords()).stream().map(s -> {
            ApAssociateWords apAssociateWords = new ApAssociateWords();
            apAssociateWords.setAssociateWords(s);
            return apAssociateWords;
        }).collect(Collectors.toList());


        return ResponseResult.okResult(list);
    }
}
